package com.cn.qgx428.lazydiary.Utils

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Created by QinX on 2017/9/19.
 */

/**
 * MD5 编码， 生成唯一识别号
 */
object MD5Utils {
    fun encrypt(url: String): String {
        var cacheKey: String
        try {
            val mDigest = MessageDigest.getInstance("MD5")
            mDigest.update(url.toByteArray())
            cacheKey = bytesToHexString(mDigest.digest())
        } catch (e: NoSuchAlgorithmException) {
            cacheKey = url.hashCode().toString()
        }

        return cacheKey
    }

    fun bytesToHexString(bytes: ByteArray): String {
        val sb = StringBuilder()
        for (i in bytes.indices) {
            val hex = Integer.toHexString(0xFF and bytes[i].toInt() )
            if (hex.length == 1) {
                sb.append('0')
            }
            sb.append(hex)
        }
        return sb.toString()
    }
}
